<template>
  <div v-if="isFaceEntry">
    <a-form
        name="basic"
        :label-col="{ span: 8 }"
        :wrapper-col="{ span: 16 }"
        autocomplete="off"
        @finish="onFinish"
        @finishFailed="onFinishFailed"
    >
      <a-form-item
          label="用户姓名"
          name="username"
      >
        <a-input v-model:value="username" />
      </a-form-item>
      <a-form-item
          label="用户岗位"
          name="position"
      >
        <a-input v-model:value="position" />
      </a-form-item>

      <a-form-item :wrapper-col="{ offset: 8, span: 16 }">
        <a-button type="primary" html-type="submit" @click="onFinish(username,position)">提交</a-button>
      </a-form-item>
    </a-form>
  </div>
  <div v-else>
  <a-layout style="width: 1200px">
    <a-layout-header style="background: #fff; padding: 0">
      <h1>人脸录入</h1>
    </a-layout-header>
    <a-layout-content style="margin: 24px 16px 0;">
      <video ref="video" :width="640" :height="480" autoplay></video>
      <br/>
      <a-button type="primary" @click="startPrediction">开始识别</a-button>
      <a-button danger @click="stopPrediction">停止识别</a-button>
    </a-layout-content>
  </a-layout>
  </div>
</template>

<script>
import { Button, message } from 'ant-design-vue';
import myAxios from "../plugins/myAxios.ts";


export default {
  name: 'FaceEntry',
  components: {
    'a-button': Button,
  },
  data() {
    return {
      stream: null,
      isPredicting: false,
      predictions: [],
      predictionResult: '',
      isFaceEntry:true,
      username:'',
      sex:'',
      position:'',
      id:'',
      countNum:0,
    };
  },
  mounted() {
    this.setupCamera();
  },
  methods: {
    async setupCamera() {
      try {
        this.stream = await navigator.mediaDevices.getUserMedia({ video: true });
        this.$refs.video.srcObject = this.stream;
      } catch (error) {
        message.error('摄像头获取失败');
        console.error('摄像头获取失败', error);
      }
    },

    captureFrame() {
      if (!this.isPredicting) return;
      const canvas = document.createElement('canvas');
      canvas.width = 640;
      canvas.height = 480;
      const context = canvas.getContext('2d');
      context.drawImage(this.$refs.video, 0, 0, canvas.width, canvas.height);
      canvas.toBlob(async (blob) => {
        const formData = new FormData();
        formData.append('image', blob, `${this.id}.jpg`);
        const response = await fetch("https://u277885-83ae-77241419.neimeng.seetacloud.com:6443/upload", {
          method: "POST",
          body: formData,
          headers: {
            'Accept': 'application/json'
          }
        });

        const result = await response.json();

        if (response.ok) {
          this.predictions.push(result.label);

          if (this.predictions.length > 5) {
            this.predictions.shift();
            this.stopPrediction();
          }
        }

        setTimeout(this.captureFrame, 1000);
      }, 'image/jpeg');
    },
    onFinish(values) {
      myAxios.post('/user/register',{
        username:this.username,
        position:this.position}).then((res)=>{
        this.id = res.data;
        this.isFaceEntry = false;
        message.success("个人信息录入完成");
      })
    },
    onFinishFailed(errorInfo) {
      console.log('Failed:', errorInfo);
    },


    stopPrediction() {
      this.isPredicting = false;
      if (this.stream) {
        this.stream.getTracks().forEach(track => {
          track.stop();
          track = null;
        });
        this.stream = null;
      }
      this.$refs.video.srcObject = null;
    },

    async startPrediction() {
      this.isPredicting = true;
      this.predictions = [];
      this.predictionResult = '';

      // 在开始预测前，尝试重新获取媒体流
      try {
        if (this.stream) {
          // 如果已有流，先释放
          this.stream.getTracks().forEach(track => track.stop());
        }
        this.stream = await navigator.mediaDevices.getUserMedia({ video: true });
        this.$refs.video.srcObject = this.stream;
      } catch (error) {
        this.isPredicting = false; // 确保状态重置
        // message.error('摄像头获取失败');
        // console.error('摄像头获取失败', error);
        return;
      }
      this.captureFrame();
    },

  },
};

</script>

<style scoped>
</style>
